package com.hzw.saas.web.admin.job.task;

import java.util.Queue;
import java.util.concurrent.CountDownLatch;

import com.hzw.saas.api.hpc.IHpcFetchService;
import com.hzw.saas.api.hpc.bo.HpcAccountRecordBo;
import com.hzw.saas.service.hpc.exception.PullHpcDetailsException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *
 * </p>
 *
 * @author sonam
 * @since 2021/5/7 13:49
 */
@Slf4j
public class Task extends AbstractTaskService {
    @Setter
    private PlatformTransactionManager transactionManager;

    @Setter
    private IHpcFetchService hpcFetchService;

    @Getter
    private Exception exception;

    @Setter
    private Queue<HpcAccountRecordBo> queue;

    public Task(CountDownLatch countDownLatch) {
        super(countDownLatch);
    }

    @Override
    protected void execute() {
        HpcAccountRecordBo accountRecordBo;
        /** 不停的取队列中取超算账号*/
        while ((accountRecordBo = queue.poll()) != null) {
            try {
                hpcFetchService.fetchHpcDetails(accountRecordBo);
            } catch (PullHpcDetailsException e) {
                // 拉取明细失败
                // 暂时忽略处理
            } catch (Exception e) {
                this.exception = e;
            } finally {
                /** 记录当天增值记录 */
                hpcFetchService.recordHpcBalance(accountRecordBo);
                /** 事务完成更新账户余额*/
                if(accountRecordBo != null) {
                    /** 开启事务*/
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    TransactionStatus status = transactionManager.getTransaction(def);
                    try {
                        hpcFetchService.updateHpcAccountBalance(accountRecordBo);
                        /** 提交事务*/
                        transactionManager.commit(status);
                    } catch (Exception e) {
                        e.printStackTrace();
                        /** 异常回滚*/
                        transactionManager.rollback(status);
                        this.exception = e;
                    }
                }
            }
        }
    }

}
